﻿<%@ WebHandler Language="C#" Class="EmployeePermitsList" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;

public class EmployeePermitsList : AjaxHandlerBase
{
    public EmployeePermitsList()
    {
        htTypePermit.Add("del", Constants.Permit_DelUserRoles);
        htTypePermit.Add("add", Constants.Permit_AddUserRoles);
    }
    
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string optype = context.Request["op"];
        switch (optype.ToLower())
        {
            case "getrole":     //得到角色数据
                GetRole(context);
                break;
            case "getlist":     //得到查询数据
                GetList(context);
                break;
            case "add":         //添加用户角色
                AddUserRole(context);
                break;
            case "del":         //删除用户角色
                DelUserRole(context);
                break;
        }        
    }
    //添加用户角色
    private void AddUserRole(HttpContext context)
    {
        try
        {
            string strSql = "";
            string UserId = context.Request.Params["UserId"];
            string rolelist = context.Request.Params["RoleIdList"];
            string[] array = rolelist.Split(',');
            rolelist = rolelist.Replace(",", "','");

            strSql += string.Format("delete Base_RoleUserRelationInfo where UserId='{0}' and RoleId in('{1}');", UserId, rolelist);
            foreach (string s in array)
            {                
                strSql += string.Format("insert into Base_RoleUserRelationInfo values(newid(),'{0}','{1}');", s, UserId);
            }
            Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.ExecuteSQL(strSql);

            Chenxin.Lib.Passport.Entity.Hr_UserInfo hrinfo = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityById(UserId);

            AddLog("" + CurrentUserInfo.UserName + "添加用户角色:员工姓名[" + hrinfo.UserName + "(" + hrinfo.UserCode+ ")]",
                    OperationType.OperationTypeComboList()["OprType_AddUserRole"].ToString());
            
            context.Response.Write(string.Format("{{success:'1',msg:'添加成功！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
    //删除用户角色
    private void DelUserRole(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Hr.DAL.Base_RoleUserRelationInfo.Delete(new Guid(modelid));

            AddLog("" + CurrentUserInfo.UserName + "删除用户角色",
                   OperationType.OperationTypeComboList()["OprType_DelUserRole"].ToString());
            
            context.Response.Write(string.Format("{{success:'1',msg:'删除成功！',data:''}}"));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }

    //得到页面查询结果
    private void GetList(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "UserId,UserCode,UserName,BelongDepart";
            string fieldtablelist = "UserId,UserCode,UserName,BelongDepart";
            string orderfield = "UserCode asc";
            string table = "Hr_UserInfo";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaId"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (UserId = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (BelongDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));

                sb.AppendFormat(" AND (BelongDepartId in (select departId from Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND BelongCompanyId = '{0}'", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND BelongCityId = '{0}'", cityId);
            else
                sb.AppendFormat(" AND BelongCompanyId = '{0}'", CurrentUserInfo.CompanyId);
            sb.Append(" and Status=1 ");
            if (!string.IsNullOrEmpty(context.Request["virtual"]))
                sb.AppendFormat(" and  IsVirtual='{0}'", context.Request["virtual"]);
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            
            //查看所有分配客需权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllUserRoles))
            {
                sb1.Append(" (1=1) ");
            }
            //查看城市分配客需权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityUserRoles))
            {
                sb1.AppendFormat(" BelongCityId= '{0}' ", CurrentUserInfo.CityId);
            }
            //查看公司分配客需权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyUserRoles))
            {
                sb1.AppendFormat(" BelongCompanyId= '{0}' ", CurrentUserInfo.CompanyId);
            }
            //查看部门分配客需权限
            //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartUserRoles))
            //{
            //    sb1.Append(" EXISTS(");
            //    sb1.Append(string.Format("Select 1 from Struct_UserDepartRelation M WHERE Hr_UserInfo.BelongDepartId=M.DepartId And M.Userid= '{0}'", CurrentUserInfo.UserId.ToString()));
            //    sb1.Append(") ");
            //}
            else
            {
                sb1.AppendFormat(" (1=0) ");
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string usercode = context.Request.QueryString["usercode"];

            if (!String.IsNullOrEmpty(usercode))
            {
                sb1.Append(string.Format(" and usercode like '%{0}%'", usercode));
            }
            string roleid = context.Request.QueryString["roleid"];
            if (!string.IsNullOrEmpty(roleid))
            {
                sb1.Append(string.Format(" and userid in (select userid from Base_RoleUserRelationInfo where RoleId='{0}')", roleid));
            }

            //判断权限范围结束////////////////////////////////////////////
            System.Data.DataSet list = null;
            list = Chenxin.Lib.Hr.DAL.Struct_UserDepartRelation.GetList(
                iPageIndex, iPageSize, orderfield, table, sb1.ToString(), fieldlist, fieldtablelist, true);

            int count = (int)list.Tables[1].Rows[0][0];
            DataTable dt =null;

            if (count > 0)
            {
                string useridList = "";
                foreach (DataRow dr in list.Tables[0].Rows)
                {
                    useridList += string.Format("'{0}',", dr["UserId"]);
                }
                if (useridList.Length > 0)
                    useridList = useridList.Substring(0, useridList.Length - 1);
                dt = Chenxin.Lib.Passport.DAL.User_Permits.GetRoleListByUserid(useridList).Tables[0];
            }            
            
            string strHtml = "";            
            
            if (!GetKeyListHtml(list,dt, out strHtml))
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml));
            }
            if(dt!=null)
                dt.Dispose();
            list.Dispose();
            list = null;
            context.Response.Write(string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }


    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist,DataTable dt, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table width=\"100%\" height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
            sb.Append("<tbody>");
            if (dt != null)
            {
                foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
                {
                    //table的员工信息头
                    sb.Append(string.Format("<tr class=\"tr_houselist\"><td>门店：{0} 工号：{1} 姓名：{2}</td></tr>", row["BelongDepart"], row["UserCode"], row["UserName"]));

                    //得到该员工所有角色数据
                    string expression = string.Format("userid='{0}'", row["UserId"]);
                    string sortOrder = "CompanyName DESC";

                    DataRow[] foundRows = dt.Select(expression, sortOrder);
                    if (foundRows.Length > 0)
                    {
                        sb.Append("<tr class=\"tr_houselist\"><td>");
                        foreach (DataRow dr in foundRows)
                        {
                            sb.Append(string.Format("<a href=\"admin/RoleMgr.aspx?RoleId={3}\">{0}({1})</a><span class=\"del_role\" name=\"{2}\" style=\"color:red; margin-left:3px;cursor:pointer; margin-right:10px;\">X</span>", dr["RoleName"], dr["CompanyName"], dr["recordid"], dr["RoleId"]));
                        }
                        sb.Append("</td></tr>");
                    }
                    else
                    {
                        sb.Append("<tr class=\"tr_houselist\"><td>暂无角色记录</td></tr>");
                    }
                }
            }
            sb.Append("</tbody></table>");            
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
    
    //根据公司ID得到角色数据
    private void GetRole(HttpContext context)
    {
        try
        {
            string companyid = context.Request.Params["companyid"];
            string strSql = string.Format("CompanyId='{0}'",companyid);
            
            List<Chenxin.Lib.Hr.Entity.Base_Permit_RoleDefine> list = Chenxin.Lib.Hr.DAL.Base_Permit_RoleDefine.GetListArray(strSql);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (list.Count > 0)
            {
                foreach (Chenxin.Lib.Hr.Entity.Base_Permit_RoleDefine r in list)
                {
                    sb.AppendFormat("{{txt:'{0}',val:'{1}'}},", r.RoleName, r.RoleId);
                }
                sb.Remove(sb.Length - 1, 1);
            }
            context.Response.Write(string.Format("{{success:'1',msg:'',data:{{items:[{0}]}}}}", sb.ToString()));
        }
        catch (Exception ex)
        {
            context.Response.Write(string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message));
        }
    }
    
}